<template>
  <div class="login_container">
    <el-row>
      <el-col :span="12">左侧</el-col>
      <el-col :span="12">
        <el-form
          class="login_form"
          :model="loginForm"
          :rules="rules"
          ref="loginForms"
        >
          <h1>Hello</h1>
          <h2>欢迎来到硅谷甄选</h2>
          <el-form-item prop="username">
            <el-input
              v-model="loginForm.username"
              :prefix-icon="User"
            ></el-input>
          </el-form-item>
          <el-form-item prop="password">
            <el-input
              type="password"
              v-model="loginForm.password"
              show-password
              :prefix-icon="Lock"
            ></el-input>
          </el-form-item>
          <el-form-item>
            <el-button
              :loading="loading"
              class="login_btn"
              type="primary"
              size="default"
              @click="login"
            >
              登录
            </el-button>
          </el-form-item>
        </el-form>
      </el-col>
    </el-row>
  </div>
</template>

<script setup lang="ts">
// Element-plus 图标
import { User, Lock } from '@element-plus/icons-vue'
import { reactive, ref } from 'vue'
// 悬浮出现在页面角落，显示全局的通知提醒消息。
import { ElNotification } from 'element-plus'
// 获取时间
import { getTime } from '@/utils/time'
//
import { useRouter } from 'vue-router'
// 账号密码仓库
import useUserStore from '@/store/modules/user'
// 定义加载效果
let loading = ref(false)

let userStore = useUserStore()
// 收集账号和密码数据
let loginForm = reactive({ username: 'admin', password: '111111' })
// 获取路由器
let $router = useRouter()
let loginForms = ref()

// 表单校验规则
let rules = reactive({
  username: [
    {
      // required: true, // 该属性是否必须
      min: 3,
      max: 10,
      message: '用户名格式不正确', // 提示信息
      trigger: ['change', 'blur'],
    },
  ],
})

// 登录按钮触发事件
let login = async () => {
  // 保障表单校验通过再发请求
  await loginForms.value.validate()

  // 加载效果：开始加载
  loading.value = true
  // 点击登录按钮
  // 请求成功->首页展示数据
  // 登录失败->弹出登录失败信息
  try {
    await userStore.userLogin(loginForm)
    $router.push('/')
    ElNotification({
      type: 'success',
      message: '登录成功',
      title: `Hi,${getTime()}好`,
    })
    // 登录成功，加载效果消失
    loading.value = false
  } catch (error) {
    ElNotification({
      type: 'error',
      message: (error as Error).message,
    })
    // 登录失败，加载效果消失
    loading.value = false
  }
}
</script>

<style scoped lang="scss">
.login_container {
  width: 100%;
  height: 100vh;
  background: url('@/assets/images/background.jpg') no-repeat;
  background-size: cover;

  .login_form {
    position: relative;
    width: 80%;
    top: 30vh;
    padding: 40px;
    background: url('@/assets/images/login_form.png') no-repeat;
    background-size: cover;

    h1 {
      color: white;
      font-size: 40px;
    }

    h2 {
      color: white;
      font-size: 20px;
      margin: 20px 0;
    }

    .login_btn {
      width: 100%;
    }
  }
}
</style>
